package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eunion.common.util.CommUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.Major;
import com.eunion.web.cms.entity.ScoreRank;
import com.eunion.web.cms.entity.spec.MajorSpec;
import com.eunion.web.cms.entity.spec.ScoreRankSpec;
import com.eunion.web.cms.service.ScoreRankService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;

/**
 * 高考分数
 */
@Controller
@RequestMapping("/api/score-ranks")
@PreAuthorize("hasAuthority('scorerank:info')")
public class ScoreRankResource extends BaseTableCommonController<ScoreRank, Long> {

    @Override
    protected BaseService<ScoreRank, Long> getBaseService() {
        return scoreRankService;
    }

    @Autowired
    private ScoreRankService scoreRankService;

    /**
     * 进入高考分数查询页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/scorerank/scorerank";
    }

    /**
     * 高考分数统计数据导入
     * @param obj
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('scorerank:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }

                // 上传文件的原始名称
                String fileNameOrg = obj.getFileNameOrg();
                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                List<ScoreRank> scoreRankList = ExcelUtil.readScoreRankData(sheet, fileNameOrg);

                List<ScoreRank> toSave = new ArrayList<>();
                List<ScoreRank> toUpdate = new ArrayList<>();
                if(scoreRankService.count() > 0) {
                    for(ScoreRank element : scoreRankList) {
                        List<ScoreRank> find = scoreRankService.findAll(ScoreRankSpec.build(element,true));
                        if(CommUtils.isEmpty(find)) {
                            toSave.add(element);
                        } else {
                            if(find.size() == 1) {
                                element.setId(find.get(0).getId());
                                toUpdate.add(element);
                            } else {
                                scoreRankService.delete(find);
                                toSave.add(element);
                            }
                        }
                    }
                }

                for(ScoreRank update : toUpdate) {
                    scoreRankService.saveAndFlush(update);
                }
                List<ScoreRank> resultList = getBaseService().save(toSave);
                if (!CommUtils.isEmpty(toSave) && (null == resultList || resultList.size() < 1)) {
                    LogUtil.get(this.getClass()).error("save scoreRankList failed");
                    setModuleStatusOK(model, "导入失败");
                } else {
                    setModuleStatusOK(model, "导入成功");
                }
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }

}
